<template>
    <el-row>
    <div style="width: 70%;">
  <el-header style="font-size: 18px; display: flex;width: 100%;">
    <div
      style="
        font-size: 18px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
      "
    >
      <strong style="margin-left: -10px">仿真配置验证-获取结果:{{props.message}}</strong>
<!--      <el-select placeholder="请选择电路" v-model="isSelect" style="margin:0 -60px 0 -60px; width: 150px;">
          <el-option
            v-for="item in resultSelect"
            :key="item"
            :label="item"
            :value="item"
            @click="getName(item)"
          />
      </el-select> -->
        <el-tag>Tips：点击未显示完全内容可查看详情</el-tag>
      <el-button
        type="primary"
        style="background-color: #003f82"
        @click="getSimulation1"
        >查询</el-button
      >
    </div>
  </el-header>
  <el-table stripe border style="margin-top: 10px" :data="response2"
  max-height="250px">
    <el-table-column
      align="center"
      label="开始时间"
      prop="begin_time"
      width="140"
    ></el-table-column>
    <el-table-column
      align="center"
      label="结束时间"
      prop="end_time"
      width="140"
    ></el-table-column>
    <el-table-column
      align="center"
      label="方法耗时"
      prop="cost_time"
      width="140"
    ></el-table-column>
      <el-table-column align="center" label="验证结果" prop="content">
        <template #default="scope">
          <div class="ellipsis" @click="showDialog(scope.row.content)">{{ scope.row.content }}</div>
        </template>
      </el-table-column>
      
  </el-table>
  </div>
  <div style="
    width: 30%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  ">
                          <a style="
      margin-bottom: -5px;
      font-size: 20px;
      margin-top:10px ;
    ">仿真验证-获取结果耗时</a>
                          <div ref="chartDom"
                              style="width: 380px; height: 280px;margin-bottom: -50px;"></div>
                      </div>
                      </el-row>
      <el-dialog 
       title="完整信息显示"
       v-model="dialogVisible" :before-close="handleClose" custom-class="custom-dialog">
        <div v-html="dialogContent"></div>
      </el-dialog>
</template>

<script setup>
import {
  watch,
  ref,
  onMounted,
  onUnmounted,
  defineProps
} from "vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import { circuitServer } from "@/server/iIndex";
import { getSimulationTextResult } from "@/server/simulation.js";
import useUserInfoStore from "@/stores/userInfo.js";
const userInfoStore = useUserInfoStore();
const userInfo = userInfoStore.info;
const response2 = ref([]);

const dialogVisible=ref(false);
const  dialogContent=ref("");

const showDialog =(content)=>{
    dialogContent.value=content;
    dialogVisible.value=true;
}

const handleClose =()=>{
    dialogVisible.value=false;
}

    let formatDates = (time) => {
        if (time !== "-" && time) {
            time = Number(time);
            if (time < 1000) {
               return time.toFixed(2) + "ms";
             } else if (time < 60000) {
               return (time / 1000).toFixed(2) + "s";
             } else {
               const minutes = Math.floor(time / 60000);
               const seconds = ((time % 60000) / 1000).toFixed(2);
               return minutes + "min " + seconds + "s";
             }
        }else {
        return "-";
    }
     };
     
const props = defineProps({
  message: String
});

const isSelect = ref('');
const resultSelect = ref([]);

const getCircuit = async () => {
  try {
    const response = await circuitServer();
    resultSelect.value = response.name;
  } catch (error) {
    ElMessage.warning("获取电路失败");
  }
};

const circuitName = ref("");
  const getName = (name) =>{
      circuitName.value=name;
  }
  
  
const getSimulation1 = async () => {
  console.log(userInfo);
  try {
      isGo.value=true
    const response = await getSimulationTextResult({user:userInfo,circuit_diagram_name:props.message});
    const formattedResponse = {
      begin_time: formatDate(response.begin_time),
      end_time: formatDate(response.end_time),
      content:
        response.content !== undefined && response.content !== null
          ? response.content
          : "-",
      cost_time: formatDates(response.cost_time),
    };
    response2.value = [formattedResponse]; // 将单个对象包装成数组
      if (
        response.content !== "计算中" &&
        response.content !== "-"
      ) {
        stopTimer1();
        isGo.value=false;
      }
  } catch (e) {
      isGo.value=false
      stopTimer1()
      ElMessage.error("操作失败")
    console.error("e:", e);
  }
};

const formatDate = (time) => {
  if (time !== "-" && time) {
    let date = new Date(Number(time));
    return date
      .toLocaleString("zh-CN", {
        hour12: false,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      })
      .replace(/,/g, " ")
      .slice(5); // 只显示月时分
  } else {
    return "-";
  }
};

// 清除定时器以防止内存泄漏
onUnmounted(() => {
    stopTimer1();
    if (myChart) {
        myChart.dispose(); // 销毁图表实例
    }

});
    onMounted(() => {
        getCircuit();
        if(isGo.value){
                startTimer1();
        }
        if (chartDom.value) {
            myChart = echarts.init(chartDom.value);
            updateChartData();
        }
    });
    

    /* -----------------Echarts代码--------*/
    const chartDom = ref(null);
    let myChart = null;
    let option = ref(null);

const isGo=ref(false)
    watch(isGo, (newValue) => {
        if (newValue) {

            startTimer1();
        } else {
            stopTimer1();
            totalSeconds.value = 0; // 重置总秒数
            updateChartData();
        }
    });

    const timerId1 = ref(null);
    const totalSeconds = ref(0);
    function startTimer1() {
        timerId1.value = setInterval(() => {
            totalSeconds.value++;
            if (totalSeconds.value % 30 === 0) {
                getSimulation1();
            }
            updateChartData();
        }, 1000);
    }

    function stopTimer1() {
        if (timerId1.value) {
            clearInterval(timerId1.value);
            timerId1.value = null;
        }
        totalSeconds.value=0;
    }


    async function updateChartData() {
        let dataSpeed = 0;
        let minutes = 0;
        let seconds = 0;

        // 如果 cost_time 存在，则使用 cost_time 的数据
        if (typeof response2.value.cost_time === "number") {
            dataSpeed = response2.value.cost_time;
            minutes = Math.floor(dataSpeed / 60);
            seconds = dataSpeed % 60;
        } else {
            // 否则，使用基于计时器的数据
            minutes = Math.floor(totalSeconds.value / 60);
            seconds = totalSeconds.value % 60;
        }

        // 确保分钟数不超过10，秒数不超过60
        minutes = minutes > 60 ? 60 : minutes;
        seconds = seconds > 60 ? 60 : seconds;

        option.value = {
            series: [{
                type: "gauge",
                min: 0,
                max: 30,
                progress: {
                    show: true,
                    width: 18,
                },
                axisLine: {
                    lineStyle: {
                        width: 15,
                    },
                },
                axisTick: {
                    show: false,
                },
                splitLine: {
                    length: 8,
                    lineStyle: {
                        width: 2,
                        color: "#999",
                    },
                },
                axisLabel: {
                    distance: 25,
                    color: "#999",
                    fontSize: 18,
                },
                anchor: {
                    show: true,
                    showAbove: true,
                    size: 20,
                    itemStyle: {
                        borderWidth: 8,
                    },
                },
                title: {
                    show: false,
                },
                detail: {
                    valueAnimation: true,
                    fontSize: 28,
                    offsetCenter: [0, "85%"],
                    formatter: function() {
                        return `${minutes} min ${seconds} sec`;
                    },
                },
                data: [{
                    value: minutes, // 使用分钟数作为图表的数据值
                }, ],
            }, ],
        };
        myChart.setOption(option.value); // 应用新的配置选项
    }
</script>

<style scoped>
    .ellipsis {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      cursor: pointer;
      display: block; /* 确保元素为块级元素 */
    }
    
    .custom-dialog >>> .el-dialog {
      width: auto; /* 让宽度自适应内容 */
      max-width: 90%; /* 最大宽度限制 */
    }
</style>
